import { BadRequestException, Injectable } from '@nestjs/common';
import { RegisterDto } from './dto/registerDto';
import { LoginDto } from './dto/loginDto';
import { PrismaService } from 'src/prisma/prisma.service';
import { hash, verify } from 'argon2';
import { JwtService } from '@nestjs/jwt';
import { RoleDto } from './dto/roleDto';
import { SetRoleDto } from './dto/setRoleDto';
@Injectable()
export class AuthService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly jwt: JwtService,
  ) {}
  //注册
  async register(registerDto: RegisterDto) {
    delete registerDto.password_confirm;
    //使用argon2加密密码
    const password = await hash(registerDto.password);
    return await this.prisma.user.create({
      data: { ...registerDto, password },
    });
  }
  //登录
  async login(loginDto: LoginDto) {
    const user = await this.prisma.user.findFirst({
      where: { username: loginDto.username },
      select: {
        id: true,
        username: true,
        avatar: true,
        password: true,
      },
    });
    if (!(await verify(user.password, loginDto.password))) {
      throw new BadRequestException('密码输入错误');
    }
    return this.token(user);
  }
  //获取所有用户（测试jwt是否可用）
  async allUser() {
    return await this.prisma.user.findMany({
      include: { roles: true },
    });
  }
  //创建role
  async createRole(role: RoleDto) {
    return await this.prisma.role.create({
      data: { name: role.name },
    });
  }
  //给用户分配role
  async setRoleToUser(id: number, roles: SetRoleDto) {
    return this.prisma.user.update({
      where: { id: +id },
      data: {
        roles: { connect: roles.roleIds.map((roleId) => ({ id: roleId })) },
      },
    });
  }
  //token加密方法
  async token({ username, id }) {
    return {
      token: await this.jwt.signAsync({
        username,
        sub: id,
      }),
    };
  }
}
